﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Diagnostics;
using System.Windows.Media;

namespace SStuff.FlowControls
{
    public class FlowPanel2D :  FlowPanelBase
    {
        private IFlowLayout2DAlgorithm _layoutAlgorithm;

        public IFlowLayout2DAlgorithm LayoutAlgorithm
        {
            get { return _layoutAlgorithm; }
            set 
            { 
                _layoutAlgorithm = value;
                InvalidateMeasure();
            }
        }


        protected override void SendAvailableSizeToAlgorithm(Size availableSize)
        {

            if (_layoutAlgorithm != null)
                _layoutAlgorithm.SetAvailableSize(availableSize);
            else
            {
                Dispatcher.BeginInvoke(
                    () =>
                InvalidateMeasure());
            }
        }








        protected override void ApplyLayout(double normalizedIndex, UIElement element, int consideredItemsCount)
        {
            if (_layoutAlgorithm != null)
            {
                _layoutAlgorithm.ComputeLayout(normalizedIndex, element as IFlowItem2D, consideredItemsCount);
            }
            else
            {
                Dispatcher.BeginInvoke(
                    () =>
                InvalidateMeasure());
            }
        }


        protected override void ApplyZOrder(IEnumerable<UIElement> children)
        {
            int zindex = 1;
            foreach (var child in children.Cast<FlowItem2D>().OrderBy(c => c.RelativeZIndex))
            {
                Canvas.SetZIndex(child, zindex++);
            }
        }
        


        protected override int GetAlgorithmMaxDisplayedItems()
        {
            if (_layoutAlgorithm == null)
                return -1;
            return _layoutAlgorithm.GetMaxDisplayedItems();
        }

        

    }
}
